package com.xxh.blog.controller;

import com.xxh.blog.utils.Result;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;

/**
 * 处理文件上传的controller
 */
@Controller
public class FileController {

    @Value("${uploadDir}")
    String uploadDir;

    @ResponseBody
    @PostMapping("/user/upload")
    public Result upload(@RequestParam(value = "file") MultipartFile file){


        if (file.isEmpty()) {
            return Result.error("上传文件失败");
            // return JsonUtil.getFailJsonObject("文件不能为空");
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();

        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 文件上传后的路径
        String filePath = uploadDir;
        // 解决中文问题，liunx下中文路径，图片显示问题
        // fileName = UUID.randomUUID() + suffixName;
        File dest = new File(filePath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return Result.ok("上传完成").put("url",fileName);
            //return JsonUtil.getSuccessJsonObject(fileName);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.ok("上传完成");
    }
}
